<?php
declare (strict_types=1);

namespace app\mall\event\listeners;

use app\common\model\payment\PaymentOrderItem;
use app\mall\model\product\Product;
use app\mall\model\product\ProductSaleCount;

class Sale
{
    public static function handle($sale)
    {
        // 数量及时间
        $order = app(PaymentOrderItem::class)->with(['main'])->where('order_sub_no', $sale->order_sub_no)->findOrEmpty();
        $num   = $order->num;
        $month = date('Ym', $order->payment_time);
        // 修改product表sale_count字段
        $prod = app(Product::class)->findOrEmpty($sale->product_id);
        if (!$prod->isEmpty()) {
            $prod->sale_count += $num;
            $prod->save();
        }
        // 修改product_sale_count表数据
        $monthSale = app(ProductSaleCount::class)->where('product_id', $sale->product_id)->where('month', $month)->findOrEmpty();
        if ($monthSale->isEmpty()) {
            ProductSaleCount::create([
                'product_id' => $sale->product_id,
                'month'      => $month,
                'count'      => $num,
            ]);
        } else {
            $monthSale->count += $num;
            $monthSale->save();
        }
    }
}